package com.ellfors.module_first.dialog_queue

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.DialogFragment
import com.ellfors.common.ext.dp2px
import com.ellfors.module_first.databinding.FragmentDialogTestBinding

class TestDialogFragment : DialogFragment(), DialogQueueManager.DialogQueueInterface {

    companion object {
        fun build(content: String): TestDialogFragment {
            val fragment = TestDialogFragment()
            fragment.arguments = Bundle().apply {
                putString("content", content)
            }
            return fragment
        }
    }

    private var mDialogQueueDismiss: (() -> Unit)? = null
    private val mContent by lazy {
        arguments?.getString("content") ?: "Null"
    }

    private val mBinding by lazy {
        FragmentDialogTestBinding.inflate(layoutInflater)
    }

    override fun onCreateView(inflater: LayoutInflater, parent: ViewGroup?, bundle: Bundle?): View {
        return mBinding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        val params = mBinding.clContainer.layoutParams
        params?.width = 300.dp2px()
        params?.height = 400.dp2px()
        mBinding.clContainer.layoutParams = params

        mBinding.tvContent.text = mContent

        mBinding.btnOk.setOnClickListener {
            queueDismiss()
        }
    }

    override fun onDestroyView() {
        listener?.onDismiss()
        listener = null
        mDialogQueueDismiss?.invoke()
        mDialogQueueDismiss = null
        super.onDestroyView()
    }

    override fun onDestroy() {
        super.onDestroy()
        listener?.onDismiss()
        listener = null
        mDialogQueueDismiss?.invoke()
        mDialogQueueDismiss = null
    }

    interface DismissListener {
        fun onDismiss()
    }

    private var listener: DismissListener? = null

    fun setDismissListener(listener: DismissListener?) {
        this.listener = listener
    }

    override fun queueShow(activity: AppCompatActivity) {
        if (activity.isFinishing || activity.supportFragmentManager.isStateSaved) {
            return
        }
        runCatching {
            show(activity.supportFragmentManager, "webview_dialog${System.currentTimeMillis()}")
        }
    }

    override fun queueDismiss() {
        dismiss()
    }

    override fun triggerQueueDismiss(block: (() -> Unit)?) {
        mDialogQueueDismiss = block
    }
}